package com.wtao.testcamera;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.media.ImageReader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.wtao.testcamera.camera.Camera2Proxy;
import com.wtao.testcamera.utils.ImageUtils;
import com.wtao.testcamera.view.AutoFitTextureView;
import com.wtao.testcamera.view.Camera2GLSurfaceView;

import java.nio.ByteBuffer;

/**
 * camera2的api，这对车机上的GLSurfaceView的例子
 * 主要加上拍照的功能，并且换成了camera2的api,经过测试，在平板ok，在车机的camera上id为0的会镜像问题（解决方法是逆反写点的顺序）
 */
public class GLSurfaceViewActivity extends AppCompatActivity implements View.OnClickListener{
    private ImageView mSwitchCameraIv;
    private ImageView mTakePictureIv;
    String TAG = "GLSurfaceViewActivity";

    private Camera2GLSurfaceView mCameraView;

    private Camera2Proxy mCameraProxy;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_glsurface_view);
        initView();
    }

    private void initView() {

        mSwitchCameraIv = findViewById(R.id.switch_camera);
        mSwitchCameraIv.setOnClickListener(this);
        mTakePictureIv = findViewById(R.id.take_photo);
        mTakePictureIv.setOnClickListener(this);

        mCameraView = findViewById(R.id.id_gl_sv);
        mCameraProxy = mCameraView.getCameraProxy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.switch_camera:
                mCameraProxy.switchCamera(mCameraView.getWidth(), mCameraView.getHeight());
                mCameraProxy.startPreview();
                break;
            case R.id.take_photo:
                mCameraProxy.setImageAvailableListener(mOnImageAvailableListener);
                mCameraProxy.captureStillPicture(); // 拍照
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCameraProxy.stopPreview();
        mCameraProxy.releaseCamera();
    }

    private ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener
            () {
        @Override
        public void onImageAvailable(ImageReader reader) {
            new ImageSaveTask().execute(reader.acquireNextImage()); // 保存图片
        }
    };

    private class ImageSaveTask extends AsyncTask<Image, Void, String> {

        @Override
        protected String doInBackground(Image... images) {
            ByteBuffer buffer = images[0].getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);

            long time = System.currentTimeMillis();
            if (mCameraProxy.isFrontCamera()) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                Log.d(TAG, "BitmapFactory.decodeByteArray time: " + (System.currentTimeMillis() - time));
                time = System.currentTimeMillis();
                // 前置摄像头需要左右镜像
                Bitmap rotateBitmap = ImageUtils.rotateBitmap(bitmap, 0, true, true);
                Log.d(TAG, "rotateBitmap time: " + (System.currentTimeMillis() - time));
                time = System.currentTimeMillis();
                String path = ImageUtils.saveBitmap(rotateBitmap);
                Log.d(TAG, "saveBitmap time: " + (System.currentTimeMillis() - time));
                rotateBitmap.recycle();
                images[0].close();
                return path;
            } else {
                images[0].close();
                String path = ImageUtils.saveImage(bytes);
                Log.d(TAG, "saveBitmap time: " + (System.currentTimeMillis() - time));
                return path;
            }


        }

        @Override
        protected void onPostExecute(String path) {
            Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
            intent.putExtra("path", path);
            startActivity(intent);
        }
    }

}